package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShopCarMapper;
import com.sky.service.ShopoingCarService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShopoingCarServicelmpl implements ShopoingCarService {
    @Autowired
    private ShopCarMapper shopCarMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Override
    public void insert(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart=new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shopCarMapper.list(shoppingCart);
        if(list!=null && list.size()>0){
            ShoppingCart shoppingCart1 = list.get(0);
            shoppingCart1.setNumber(shoppingCart1.getNumber()+1);
            shopCarMapper.update(shoppingCart1);
        }else{
            Long dishId = shoppingCartDTO.getDishId();
            if(dishId!=null){
                Dish byId = dishMapper.getById(dishId);
                shoppingCart.setName(byId.getName());
                shoppingCart.setImage(byId.getImage());
                shoppingCart.setAmount(byId.getPrice());
            }else{
                Long setmealId = shoppingCartDTO.getSetmealId();
                Setmeal byId = setmealMapper.getById(setmealId);
                shoppingCart.setName(byId.getName());
                shoppingCart.setImage(byId.getImage());
                shoppingCart.setAmount(byId.getPrice());
            }
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shopCarMapper.insert(shoppingCart);
        }
    }

    @Override
    public List<ShoppingCart> list() {
        List<ShoppingCart> list = shopCarMapper.ByUserId(BaseContext.getCurrentId());
        return list;
    }

    @Override
    public void clean() {
        shopCarMapper.delCar(BaseContext.getCurrentId());
    }

    @Override
    public void clean1(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart=new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shopCarMapper.list(shoppingCart);
        if(list.get(0).getNumber()>1){
            list.get(0).setNumber(list.get(0).getNumber()-1);
            shopCarMapper.update(list.get(0));
        }else{
            shopCarMapper.clean1(shoppingCart);
        }

    }
}
